<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      title="答案设置"
      width="80%"
      :before-close="handleClose"
    >
      <el-form
        :model="answerSetUpForm"
        :rules="answerSetUpFormRules"
        ref="answerSetUpFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="问题标题" required>
          {{ questionTitle }}
        </el-form-item>
        <el-form-item label="答案一级分类" prop="answer_class">
          <el-select
            v-model="answerSetUpForm.answer_class"
            placeholder="请选择"
            filterable
            clearable
            @change="
              (val) => {
                changeClass(val)
              }
            "
            value-key="id"
          >
            <el-option
              v-for="item in firstClassArr"
              :key="item.id"
              :label="item.name"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="答案二级分类"
          prop="answer_class_two"
          v-show="secondClassArr.length > 0"
          :rules="
            secondClassArr.length > 0
              ? [
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }
                ]
              : []
          "
        >
          <el-select
            v-model="answerSetUpForm.answer_class_two"
            placeholder="请选择"
            filterable
            clearable
            @change="$forceUpdate()"
          >
            <el-option
              v-for="item in secondClassArr"
              :key="item.id"
              :label="item.name"
              :value="
                typeof answerSetUpForm.answer_class_two == 'string'
                  ? item.id + ''
                  : item.id
              "
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设置答案" prop="answer_data">
          <el-link
            :underline="false"
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="addAnswer"
            >增加答案</el-link
          >
          <div
            class="dash-border"
            v-for="(aitem, aindex) in answerDatas"
            :key="aindex"
          >
            <el-form
              :ref="'conditionFormRef' + aindex"
              :model="aitem.formModel"
              style="width: 100%; margin: 0"
            >
              <el-row>
                <el-col :span="20">
                  <el-row :gutter="10">
                    <el-col style="width: 90px"
                      >{{ aindex + 1 }}、符合以下</el-col
                    >
                    <el-col style="width: 90px">
                      <el-form-item prop="answer_condition">
                        <el-select
                          v-model="aitem.formModel.answer_condition"
                          placeholder="请选择"
                          filterable
                        >
                          <el-option
                            key="1"
                            label="全部"
                            :value="
                              typeof aitem.formModel.answer_condition ==
                              'string'
                                ? '1'
                                : 1
                            "
                          >
                          </el-option>
                          <el-option
                            key="2"
                            label="任一"
                            :value="
                              typeof aitem.formModel.answer_condition ==
                              'string'
                                ? '2'
                                : 2
                            "
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col style="width: 136px">条件时显示此答案：</el-col>
                  </el-row>
                </el-col>
                <el-col :span="4" style="text-align: right">
                  <el-link
                    type="danger"
                    icon="el-icon-delete"
                    :underline="false"
                    @click="deleteQuestion(aindex)"
                    >删除</el-link
                  >
                </el-col>
              </el-row>

              <el-row>
                <el-table
                  :data="aitem.formModel.condition"
                  style="width: 100%"
                  :row-class-name="tableRowClassName"
                  :show-header="false"
                >
                  <el-table-column>
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'condition.' + scope.$index + '.question_id'"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change'
                          }
                        ]"
                      >
                        <el-select
                          v-model="scope.row.question_id"
                          placeholder="请选择问题"
                          filterable
                          clearable
                          @change="getOptions(scope.row)"
                        >
                          <el-option
                            v-for="(item, index) in questionBefore"
                            :key="index"
                            :label="index + 1 + '.' + item.title"
                            :value="
                              typeof scope.row.question_id == 'string'
                                ? item.id + ''
                                : item.id
                            "
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="
                          'condition.' + scope.$index + '.select_condition'
                        "
                        :rules="
                          scope.row.question_id != ''
                            ? [
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change'
                                }
                              ]
                            : []
                        "
                      >
                        <el-select
                          v-model="scope.row.select_condition"
                          placeholder="请选择"
                          filterable
                          clearable
                          @change="$forceUpdate()"
                        >
                          <el-option
                            v-for="(item, index) in scope.row.conditionOptions"
                            :key="index"
                            :label="item.name"
                            :value="
                              typeof scope.row.select_condition == 'string'
                                ? item.id + ''
                                : item.id
                            "
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot-scope="scope">
                      <el-row v-show="scope.row.select_condition == 3">
                        <el-col :span="9">
                          <el-form-item
                            :prop="
                              'condition.' + scope.$index + '.special_option'
                            "
                            :rules="
                              scope.row.select_condition == 3
                                ? [
                                    {
                                      required: true,
                                      message: '请选择',
                                      trigger: 'change'
                                    }
                                  ]
                                : []
                            "
                          >
                            <el-select
                              v-model="scope.row.special_option"
                              placeholder="请选择"
                              filterable
                              clearable
                            >
                              <el-option key="1" label="数字" value="1">
                              </el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="7">
                          <el-form-item
                            :prop="'condition.' + scope.$index + '.range_start'"
                            :rules="
                              scope.row.special_option == 1
                                ? [
                                    {
                                      required: true,
                                      message: '请选择',
                                      trigger: 'change'
                                    },
                                    {
                                      type: 'number',
                                      message: '必须为数字值'
                                    }
                                  ]
                                : []
                            "
                          >
                            <el-input
                              placeholder="请输入范围"
                              v-model.number="scope.row.range_start"
                              oninput="value=value.replace(/\D/g,'')"
                            ></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col class="line" :span="1">-</el-col>
                        <el-col :span="7">
                          <el-form-item
                            :prop="'condition.' + scope.$index + '.range_end'"
                            :rules="
                              scope.row.special_option == 1
                                ? [
                                    {
                                      required: true,
                                      message: '请选择',
                                      trigger: 'change'
                                    },
                                    {
                                      type: 'number',
                                      message: '必须为数字值'
                                    }
                                  ]
                                : []
                            "
                          >
                            <el-input
                              placeholder="请输入范围"
                              v-model.number="scope.row.range_end"
                              oninput="value=value.replace(/\D/g,'')"
                            ></el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-form-item
                        :prop="'condition.' + scope.$index + '.select_option'"
                        v-show="
                          scope.row.type != 3 &&
                          (scope.row.select_condition == 1 ||
                            scope.row.select_condition == 2)
                        "
                        :rules="
                          scope.row.type != 3 &&
                          (scope.row.select_condition == 1 ||
                            scope.row.select_condition == 2)
                            ? [
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change'
                                }
                              ]
                            : []
                        "
                      >
                        <el-select
                          v-model="scope.row.select_option"
                          placeholder="请选择"
                          filterable
                          clearable
                          :multiple="scope.row.type == 2"
                          collapse-tags
                          v-if="update"
                          @change="optionChange(scope.row)"
                        >
                          <el-option
                            v-for="(item, index) in scope.row.optionArr"
                            :key="index"
                            :label="item.content"
                            :value="
                              typeof scope.row.select_option == 'string'
                                ? item.id + ''
                                : item.id
                            "
                          >
                          </el-option>
                          <el-option label="任意选项" value="any"></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column width="100px">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        @click="
                          deleteCondition(
                            scope.$index,
                            aitem.formModel.condition
                          )
                        "
                        v-show="aitem.formModel.condition.length > 1"
                        >删除</el-button
                      >
                      <el-button
                        type="text"
                        @click="
                          addCondition(
                            scope.$index,
                            aindex,
                            aitem.formModel.condition
                          )
                        "
                        >增加</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>

              <el-row v-loading="aitem.formModel.quillUpdateImg">
                <el-col :span="3">问题答案：</el-col>
                <el-col :span="21">
                  <el-form-item
                    prop="answer"
                    :rules="[
                      {
                        required: true,
                        message: '请输入',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <quill-editor
                      v-model="aitem.formModel.answer"
                      :ref="'myQuillEditor' + aindex"
                      :options="editorOption"
                      @blur="onEditorBlur($event)"
                      @focus="onEditorFocus($event, aindex)"
                      @ready="onEditorReady($event)"
                      @change="onEditorChange($event, aitem.formModel)"
                      class="editor space-ql-editor"
                    ></quill-editor>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button class="theme-background-color" @click="saveAnswerInfo"
          >保 存</el-button
        >
      </span>
    </el-dialog>

    <!-- 图片上传组件辅助-->
    <el-upload
      class="avatar-uploader"
      :action="ossUrl"
      :headers="ossHeader"
      :show-file-list="false"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="beforeUpload"
    >
    </el-upload>
  </div>
</template>

<script>
import toolbarOptions from '../../assets/js/quillToolbar.js'
export default {
  props: {
    answerSetUpDialogVisible: {
      type: Boolean,
      default: function () {
        return {}
      }
    },
    questionIdNow: {
      type: Number,
      default: function () {
        return {}
      }
    },
    // 所有的问题数据
    questionInfo: {
      type: Array,
      default: function () {
        return {}
      }
    },
    answerObject: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      visible: this.answerSetUpDialogVisible,
      questionType: '',
      questionTitle: '',

      answerSetUpForm: {
        answer_class: '',
        answer_class_two: '',
        answer_data: [
          {
            formModel: {
              answer_condition: '1',
              answer: '',
              condition: [{ id: '' }],
              quillUpdateImg: false
            }
          }
        ]
      },
      answerSetUpFormRules: {
        answer_class: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      firstClassArr: [],
      secondClassArr: [],

      answerDatas: [
        {
          formModel: {
            answer_condition: '1',
            answer: '',
            condition: [{ id: '' }],
            quillUpdateImg: false
          }
        }
      ],

      questionBefore: [],
      update: true, // 控制多选变化时不渲染组件，计算完再渲染组件
      selectChange: '',

      //富文本编辑器配置
      editorOption: {
        //主题
        theme: 'snow',
        placeholder: '请输入答案',
        //  富文本编辑器配置
        modules: {
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      // quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画
      ossUrl: this.GLOBAL.ossUrl,
      ossHeader: this.GLOBAL.ossHeader,

      activIndex: '' // 当前激活的富文本框行数
    }
  },
  created() {
    this.getClasses()
  },
  methods: {
    async getClasses() {
      const { data: res } = await this.$http.post(
        '/admin/question_manage/getAnswerClass'
      )
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.firstClassArr = res.data
      console.log(this.firstClassArr)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.$refs.answerSetUpFormRef.resetFields()
          this.$emit('update:answerSetUpDialogVisible', false)
          done()
        })
        .catch((_) => {})
    },
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    async deleteCondition(index, data) {
      const confirmResult = await this.$confirm(
        '是否确认删除该条件？删除后不可恢复',
        '删除条件',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      data.splice(index, 1)
    },
    async deleteQuestion(aindex) {
      const confirmResult = await this.$confirm(
        '是否确认删除该答案？删除后不可恢复',
        '删除条件',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      this.answerDatas.splice(aindex, 1)
    },
    addCondition(index, aindex, data) {
      if (!this.validateField('conditionFormRef' + aindex)) {
        return
      }
      data.splice(index + 1, 0, {
        id: '',
        question_id: '',
        select_condition: '',
        special_option: '',
        range_start: '',
        range_end: '',
        select_option: ''
      })
    },
    optionChange(row) {
      // console.log(row.select_option)
      // 多选题
      if (this.questionType == 2) {
        let len = row.select_option.length
        // 选择了多个选项，且最后一个选项是任意选项
        if (len > 1 && row.select_option[len - 1] == 'any') {
          // 取消其他选项的选中状态
          row.select_option = ['any']
        } else if (len == 2 && row.select_option[0] == 'any') {
          // 当选了两个选项的时候，如果第一个选项是任意选项，则取消任意选项的选中状态
          row.select_option.shift()
        }
      }
    },
    closeDialog() {
      this.$emit('update:answerSetUpDialogVisible', false)
    },
    // 对部分表单字段进行校验
    validateField(form, index = '') {
      // console.log(form)
      let result = true
      for (let item of this.$refs[form][0].fields) {
        // console.log(item)
        // if (item.prop.split('.')[1] == index) {
        this.$refs[form][0].validateField(item.prop, (error) => {
          // console.log(error)
          if (error != '' && error != undefined) {
            result = false
          }
        })
        // }
        if (!result) break
      }
      return result
    },
    checkShowDuplicates(data) {
      console.log(data)
      let tempArray = []
      for (let index = 0; index < data.length; index++) {
        for (let j = 0; j < tempArray.length; j++) {
          if (data[index].question_id == tempArray[j].question_id) {
            if (data[index].select_condition == tempArray[j].select_condition) {
              if (data[index].type == 1) {
                if (data[index].select_option == tempArray[j].select_option) {
                  return index
                }
              } else if (data[index].type == 2) {
                // 多选题
                console.log(data[index].select_option)
                // 得先排序再转字符串再比较
                if (
                  data[index].select_option.sort().toString() ==
                  tempArray[j].select_option.sort().toString()
                ) {
                  return index
                }
              } else {
                // 问答题
                return index
              }
            }
          }
        }
        tempArray.push(data[index])
      }
      return ''
    },
    checkAnswerArray(originData, newData) {
      let originDataTemp = []
      for (let i = 0; i < originData.length; i++) {
        if (originData[i].type == 2) {
          // 多选题
          originDataTemp.push({
            question_id: originData[i].question_id + '',
            select_condition: originData[i].select_condition + '',
            select_option: originData[i].select_option.sort().toString()
          })
        } else {
          if (originData[i].select_condition == 3) {
            // 范围
            originDataTemp.push({
              question_id: originData[i].question_id + '',
              range_end: originData[i].range_end + '',
              range_start: originData[i].range_start + '',
              select_condition: originData[i].select_condition + '',
              select_option: originData[i].select_option + ''
            })
          } else {
            originDataTemp.push({
              question_id: originData[i].question_id + '',
              select_condition: originData[i].select_condition + '',
              select_option: originData[i].select_option + ''
            })
          }
        }
      }
      let newDataTemp = []
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].type == 2) {
          // 多选题
          newDataTemp.push({
            question_id: newData[i].question_id + '',
            select_condition: newData[i].select_condition + '',
            select_option: newData[i].select_option.sort().toString()
          })
        } else {
          if (newData[i].select_condition == 3) {
            // 范围
            newDataTemp.push({
              question_id: newData[i].question_id + '',
              range_end: newData[i].range_end + '',
              range_start: newData[i].range_start + '',
              select_condition: newData[i].select_condition + '',
              select_option: newData[i].select_option + ''
            })
          } else {
            newDataTemp.push({
              question_id: newData[i].question_id + '',
              select_condition: newData[i].select_condition + '',
              select_option: newData[i].select_option + ''
            })
          }
        }
      }

      // 按question_id排序再校验
      originDataTemp.sort((a, b) =>
        a['question_id'] > b['question_id'] ? 1 : -1
      )
      newDataTemp.sort((a, b) => (a['question_id'] > b['question_id'] ? 1 : -1))
      console.log(JSON.stringify(originDataTemp), JSON.stringify(newDataTemp))
      if (JSON.stringify(originDataTemp) == JSON.stringify(newDataTemp)) {
        return false
      }
      return true
    },
    saveAnswerInfo() {
      this.$refs.answerSetUpFormRef.validate(async (valid) => {
        if (!valid) return

        if (this.answerDatas.length > 0) {
          for (let i = 0; i < this.answerDatas.length; i++) {
            if (!this.validateField('conditionFormRef' + i)) {
              return
            }
          }
        }
        console.log(this.answerSetUpForm)

        let transferData = []
        // 校验重复项
        for (let i = 0; i < this.answerDatas.length; i++) {
          let line = this.checkShowDuplicates(
            this.answerDatas[i]['formModel']['condition']
          )
          // console.log(line)
          if (line) {
            return this.$message.error(
              '第' + (i + 1) + '个答案的第' + (line + 1) + '行为重复项'
            )
          }
          for (let j = 0; j < transferData.length; j++) {
            console.log(
              this.answerDatas[i]['formModel']['condition'],
              transferData[j]['condition']
            )
            if (
              !this.checkAnswerArray(
                this.answerDatas[i]['formModel']['condition'],
                transferData[j]['condition']
              ) &&
              this.answerDatas[i]['formModel']['answer'] ==
                transferData[j]['answer']
            ) {
              return this.$message.error('第' + (i + 1) + '个答案重复了')
            }
          }
          transferData.push({
            answer_condition: this.answerDatas[i]['formModel'].answer_condition,
            answer: this.answerDatas[i]['formModel'].answer,
            condition: this.answerDatas[i]['formModel'].condition
          })
        }

        for (let i = 0; i < transferData.length; i++) {
          for (let j = 0; j < transferData[i].condition.length; j++) {
            let option_temp = transferData[i].condition[j].select_option
            console.log(transferData[i].condition[j].select_option, option_temp)
            if (Array.isArray(option_temp)) {
              option_temp = option_temp.join(',')
              transferData[i].condition[j].select_option = option_temp
            }
          }
        }

        // console.log(this.answerSetUpForm)
        let answerDataShow = {
          answer_class: this.answerSetUpForm.answer_class.id + '',
          answer_class_two: this.answerSetUpForm.answer_class_two,
          answer_data: transferData
        }
        console.log(answerDataShow)
        this.$emit('showAnswerData', answerDataShow)
        this.visible = false
        this.$emit('update:answerSetUpDialogVisible', false)
      })
    },
    //失去焦点事件
    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
    //获得焦点事件
    onEditorFocus(quill, index) {
      console.log('editor focus!', quill)
      this.activIndex = index
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
    //内容改变事件
    onEditorChange({ quill, html, text }, data) {
      console.log('editor change!', quill, html, text)
      data.answer = html
    },
    // 上传图片前
    beforeUpload(res, file) {
      // 显示loading动画
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccess(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      console.log(this.$refs)
      let quill = this.$refs['myQuillEditor' + this.activIndex][0].quill
      // 如果上传成功
      if (Number.parseInt(res.code) === 10001) {
        console.log(res.data.url)
        // 获取光标所在位置
        let length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.data.url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadError(res, file) {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    addAnswer() {
      if (this.answerDatas.length > 0) {
        let index = this.answerDatas.length - 1
        if (!this.validateField('conditionFormRef' + index)) {
          return
        }
        if (this.answerDatas[index]['formModel']['answer'] == '') {
          return this.$message.error('请输入第' + (index + 1) + '个答案')
        }
      }
      console.log(this.answerDatas[this.answerDatas.length - 1])
      // 校验上一条数据
      this.answerDatas.splice(this.answerDatas.length, 0, {
        formModel: {
          answer_condition: '1',
          answer: '',
          condition: [{ id: '' }],
          quillUpdateImg: false
        }
      })
    },
    changeClass(val) {
      console.log(val)
      this.$set(this.answerSetUpForm, 'answer_class_two', '')
      if (val.child.length > 0) {
        this.secondClassArr = val.child
      } else {
        this.secondClassArr = []
      }
    },
    displayRequiredData() {
      var sortNow = ''
      for (let i = 0; i < this.questionInfo.length; i++) {
        // 当前问题类型
        if (this.questionIdNow == this.questionInfo[i].id) {
          this.questionType = this.questionInfo[i].type
          this.questionTitle = this.questionInfo[i].title
          sortNow = i
          break
        }
      }
      this.questionBefore = []
      for (let i = 0; i < this.questionInfo.length; i++) {
        // 当前问题之前的问题（包括自己）
        if (i <= sortNow) {
          this.questionBefore.push(this.questionInfo[i])
        }
      }
      // console.log(this.questionInfo, this.questionIdNow)
      // console.log(this.questionBefore)
    },
    selectDataById(id) {
      for (let i = 0; i < this.questionInfo.length; i++) {
        if (id == this.questionInfo[i].id) {
          return this.questionInfo[i]
        }
      }
    },
    getOptions(row) {
      this.$set(row, 'select_option', [])
      this.handleChangeData(row)
    },
    handleChangeData(row) {
      const data = this.selectDataById(row.question_id)
      this.selectChange = data.type
      if (data.type == 3) {
        row.conditionOptions = [
          { id: 1, name: '显示' },
          { id: 2, name: '未显示' },
          { id: 3, name: '范围' }
        ]
      } else {
        row.conditionOptions = [
          { id: 1, name: '选中' },
          { id: 2, name: '未选中' }
        ]

        row.optionArr = data.option_data
      }
      row.type = data.type
    },
    editData() {
      console.log(this.answerObject)
      if (JSON.stringify(this.answerObject) != '{}') {
        const answer_data = JSON.parse(
          JSON.stringify(this.answerObject.answer_data)
        )

        console.log(this.firstClassArr)
        for (let i = 0; i < this.firstClassArr.length; i++) {
          if (this.answerObject.answer_class == this.firstClassArr[i].id) {
            this.secondClassArr = this.firstClassArr[i].child
            this.answerSetUpForm.answer_class = {
              id: this.firstClassArr[i].id,
              name: this.firstClassArr[i].name,
              child: this.firstClassArr[i].child
            }
            break
          }
        }
        this.answerSetUpForm.answer_class_two =
          this.answerObject.answer_class_two
        this.answerSetUpForm.answer_data = answer_data
        console.log(this.answerSetUpForm)
        let temp = []
        for (let i = 0; i < answer_data.length; i++) {
          temp.push({
            formModel: {
              answer_condition: answer_data[i].answer_condition,
              answer: answer_data[i].answer,
              condition: answer_data[i].condition,
              quillUpdateImg: false
            }
          })
        }

        for (let i = 0; i < temp.length; i++) {
          for (let j = 0; j < temp[i].formModel.condition.length; j++) {
            const data = this.selectDataById(
              temp[i].formModel.condition[j].question_id
            )
            let select_option = temp[i].formModel.condition[j].select_option

            if (data.type == 2) {
              select_option = select_option.split(',')
              for (let k = 0; k < select_option.length; k++) {
                select_option[k] = parseInt(select_option[k])
              }
              temp[i].formModel.condition[j].select_option = select_option
            }
          }
        }
        this.answerDatas = temp
        for (let i = 0; i < this.answerDatas.length; i++) {
          const condition = this.answerDatas[i].formModel.condition
          for (let j = 0; j < condition.length; j++) {
            if (condition[j].select_condition == 3) {
              condition[j].special_option = '1'
            }

            this.handleChangeData(condition[j])
          }
        }
      }
    }
  },
  watch: {
    answerSetUpDialogVisible() {
      this.visible = this.answerSetUpDialogVisible
      if (this.visible) {
        this.getClasses()
        this.displayRequiredData()
        // 编辑
        this.editData()
      } else {
        this.$refs.answerSetUpFormRef.resetFields()
        this.answerDatas = [
          {
            formModel: {
              answer_condition: '1',
              answer: '',
              condition: [{ id: '' }],
              quillUpdateImg: false
            }
          }
        ]
      }
    },
    selectChange() {
      this.update = false
      setTimeout(() => {
        this.update = true
      })
    },
    answerDatas: {
      handler: function (val, oldval) {
        this.answerSetUpForm.answer_data = val
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  margin: 0px 15px;
  .el-select {
    width: 100%;
  }
}
.line {
  text-align: center;
  line-height: 40px;
}
/deep/.el-dialog__footer {
  text-align: center;
  .el-button {
    width: 160px;
  }
}
/deep/.editor {
  line-height: normal !important;
  height: 200px;
}
/deep/.ql-container {
  height: 130px;
}
/deep/.el-table .el-table__cell {
  padding: 5px 0;
  .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
}
.dash-border {
  border: 1px dashed #dbdbdb;
  padding: 20px 15px;
  margin-bottom: 10px;
}
</style>
